﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Threading;
using System.Windows.Threading;
using System.IO;
using System.Windows.Forms;
using System.Windows.Media.Animation;
using System.Collections.ObjectModel;

namespace FAST
{
	/// <summary>
	/// Interaction logic for HomeControl.xaml
	/// </summary>
    public partial class HomeControl : System.Windows.Controls.UserControl
    {
        private FolderBrowserDialog folderDialogBox = new FolderBrowserDialog();
        private Main ctrl;
        private string currentState = "";
        private List<FilesHandler> leftListDetails;
        private List<FilesHandler> rightListDetails;

        private bool isOk;

        //CONFLICT
        private List<ConflictsObject> conflictList;

        public HomeControl()
        {
            ctrl = new Main();
            this.InitializeComponent();
            refreshSyncTool();
        }

        public void setCurrentState(string state)
        {
            currentState = state;
            refreshSyncTool();
        }
        public string getCurrentState()
        {
            return currentState;
        }
        private void btnStart_LeftBrowse_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            // TODO: Add event handler implementation here.
            if (folderDialogBox.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                String leftpath = folderDialogBox.SelectedPath;
                this.cbxLeftFolder.Text = leftpath;
                this.cbxLeftFolder.Items.Add(leftpath);
            }
        }
        private void btnStart_RightBrowse_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            // TODO: Add event handler implementation here.
            if (folderDialogBox.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                String rightpath = folderDialogBox.SelectedPath;
                this.cbxRightFolder.Text = rightpath;
                this.cbxRightFolder.Items.Add(rightpath);
            }
        }	
        private void btnStartFolderPairCompare_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            // TODO: Add event handler implementation here.
            try
            {
                String lRoot = cbxLeftFolder.Text;
                String rRoot = cbxRightFolder.Text;
                verifyLocation(lRoot, rRoot);
                folderCompareAction(lRoot, rRoot);
                          

                //refreshSyncTool();
            }
            catch (CustomException ex) //catch custom exception
            {
                System.Windows.Forms.MessageBox.Show(ex.Message, "Folder(s) not existent/selected error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            catch (Exception ex) //catch any uncaught exceptions
            {
                Console.WriteLine(ex.ToString());
            }
        }	
        private void folderCompareAction(string leftRootPath, string rightRootPath)
        {
            btnStartFolderPairCompare.IsEnabled = false;
            listviewLeftFolder.IsEnabled = false;
            listviewRightFolder.IsEnabled = false;
            ctrl = new Main();
            new Thread(
             delegate()
             {
                 Dispatcher.BeginInvoke(DispatcherPriority.Background, (SendOrPostCallback)delegate { prgProgress2.IsIndeterminate = true; }, null);
                 Dispatcher.BeginInvoke(DispatcherPriority.Background, (SendOrPostCallback)delegate { txtProgress2.Text = "Comparing..."; }, null);

                 leftListDetails = ctrl.generateLeftList();
                 rightListDetails = ctrl.generateRightList();
                 ctrl.previewWithoutOS(leftRootPath, rightRootPath);
                 Dispatcher.BeginInvoke(DispatcherPriority.Background, (SendOrPostCallback)delegate
                 {
                     clearFolderCompareListView();
                     populateLeftRightArrayList();
                     btnStartFolderPairCompare.IsEnabled = true;
                     listviewLeftFolder.IsEnabled = true;
                     listviewRightFolder.IsEnabled = true;
                 }, null);

                 Dispatcher.BeginInvoke(DispatcherPriority.Background, (SendOrPostCallback)delegate { prgProgress2.IsIndeterminate = false; }, null);
                 Dispatcher.BeginInvoke(DispatcherPriority.Background, (SendOrPostCallback)delegate { txtProgress2.Text = "Completed."; }, null);
             }
             ).Start();
        }
        private void verifyLocation(string lRoot, String rRoot)
        {
            //trim the last "\" if got any - for exact checking of same path.
            if (lRoot.EndsWith("\\"))
            {
                lRoot = lRoot.TrimEnd('\\');
            }
            if (rRoot.EndsWith("\\"))
            {
                rRoot = rRoot.TrimEnd('\\');
            }

            if ((String.IsNullOrEmpty(lRoot)) && (String.IsNullOrEmpty(rRoot)))
            {
                throw new CustomException("You have not selected two valid folders path!Please try again.");
            }

            if (String.IsNullOrEmpty(lRoot))
            {
                throw new CustomException("You have not selected valid left folder path!Please try again.");
            }
            else if (String.IsNullOrEmpty(rRoot))
            {
                throw new CustomException("You have not selected valid right folder path!Please try again.");
            }
            else if (!Directory.Exists(lRoot))
            {
                //txtLFolder.Text = "";
                throw new CustomException("You have selected a non existent left folder path!Please try again.");

            }
            else if (!Directory.Exists(rRoot))
            {
                //txtRFolder.Text = "";
                throw new CustomException("You have selected a non existent right folder path!Please try again.");
            }

            if (String.Equals(lRoot, rRoot, StringComparison.OrdinalIgnoreCase))
            {
                //txtLFolder.Text = "";
                //txtRFolder.Text = "";
                throw new CustomException("You have selected two same folders path!Please try again.");
            }
            else if (lRoot.Contains(rRoot + "\\"))
            {
                string[] folders = lRoot.Split('\\');
                //Check recursive parent folder.
                throw new CustomException("You have selected right path as a parent folder of the left path! Please select another location again.");
            }
            else if (rRoot.Contains(lRoot + "\\"))
            {
                //Check recursive child folder.
                throw new CustomException("You have selected right path as a child folder of the left path! Please select another location again.");
            }
        }
        private void ListViewFP_DoubleClick(object sender, MouseButtonEventArgs e)
        {
            populateFolderPairsListView();
            if (
                Directory.Exists(((FolderPair)((System.Windows.Controls.ListViewItem)sender).Content).FPLeftPath)
                &&
                Directory.Exists(((FolderPair)((System.Windows.Controls.ListViewItem)sender).Content).FPRightPath)
            )//Exception to check if folder pair folder paths exist in operating system
            {
                ctrl.loadFolderPairByName(((FolderPair)((System.Windows.Controls.ListViewItem)sender).Content).FPName);
                refreshSyncTool();
				setCurrentState("ViewLast");
	            VisualStateManager.GoToState(this, "ViewLast", false);
                
                

            }
            else
            {
                System.Windows.Forms.MessageBox.Show("One or more folder no longer exist. Folder Pair fail to load.");//Exception to check if folder pair folder paths exist in operating system
            }
        }		
        private void populateFolderPairsListView()
        {
            folderPairs.Clear();
            Dictionary<string, FolderPairItem>.ValueCollection folderpairs = ctrl.retrieveFolderPairs().Values;

            foreach (FolderPairItem fpItem in folderpairs)
            {
                FolderPair fp = new FolderPair();
                fp.FPName = fpItem.getFolderPairName();

                string path = fpItem.getLeftFolderPath();
                if (Directory.Exists(path))
                    fp.LeftPathColor = "Green";
                else
                    fp.LeftPathColor = "Red";
                fp.FPLeftPath = path;

                path = fpItem.getRightFolderPath();
                if (Directory.Exists(path))
                    fp.RightPathColor = "Green";
                else
                    fp.RightPathColor = "Red";
                fp.FPRightPath = path;

                fp.CreatedTime = fpItem.getCreatedTimeStamp().ToString();
                fp.UpdatedTime = fpItem.getLastUpdatedTimeStamp().ToString();
                fp.IsToDelete = false;
                folderPairs.Add(fp);
            }
        }
        private void btnSync_Click(object sender, RoutedEventArgs e)
        {
            try {
                ctrl = new Main();
                bool isFirstSync;
                
                isOk = false;

                string fpName = "";
                if (FpNameLabel.Content.Equals(""))
                {
                    fpName = FPTxtBox.Text; //need to catch empty textbox exception here!
                    isFirstSync = true;
                }
                else
                    isFirstSync = false;

                string leftPath = cbxLeftFolder.Text;
                string rightPath = cbxRightFolder.Text;
                verifyLocation(leftPath, rightPath);
                

                MessageLog msgObj;
                if (isFirstSync)
                {
                    if (ctrl.isFolderPairNameUnique(fpName))
                    {
                        VisualStateManager.GoToState(this, "ViewConfilct", false);
                        currentState = "ViewConflict";

                        FPTxtBox.IsEnabled = false;
                        new Thread(
                        delegate()
                        {
                            Dispatcher.BeginInvoke(DispatcherPriority.Background, (SendOrPostCallback)delegate { prgProgress.IsIndeterminate = true; }, null);
                            Dispatcher.BeginInvoke(DispatcherPriority.Background, (SendOrPostCallback)delegate { txtProgress.Text = "Sync In Progress...";}, null);

                            msgObj = ctrl.twoWaySync(leftPath, rightPath, fpName, isFirstSync);
                            //conflictList = ctrl.getConflictList();
                            Dispatcher.BeginInvoke(DispatcherPriority.Background, (SendOrPostCallback)delegate { populateDataGrid(); btnConflict_OK.IsEnabled = true; }, null);
                            while (!isOk) { };
                            Dispatcher.BeginInvoke(DispatcherPriority.Background, (SendOrPostCallback)delegate { int errors = batchUILogUpdate(msgObj); this.refreshSyncTool(); }, null);
                            //Dispatcher.BeginInvoke(DispatcherPriority.Background, (SendOrPostCallback)delegate { btnSync.IsEnabled = true; }, null);

                            Dispatcher.BeginInvoke(DispatcherPriority.Background, (SendOrPostCallback)delegate { prgProgress.IsIndeterminate = false; }, null);
                            Dispatcher.BeginInvoke(DispatcherPriority.Background, (SendOrPostCallback)delegate { txtProgress.Text = "Completed."; }, null);
                        }
                        ).Start();
                    }
                    else
                    {
                        System.Windows.Forms.MessageBox.Show("Please enter a unique folder pair name.");
                    }
                }
                else
                {
                    VisualStateManager.GoToState(this, "ViewConfilct", false);
                    currentState = "ViewConflict";

                    new Thread (
                    delegate()
                    {
                        Dispatcher.BeginInvoke(DispatcherPriority.Background, (SendOrPostCallback)delegate { prgProgress.IsIndeterminate = true; }, null);
                        Dispatcher.BeginInvoke(DispatcherPriority.Background, (SendOrPostCallback)delegate { txtProgress.Text = "Sync In Progress..."; }, null);

                        msgObj = ctrl.twoWaySync(leftPath, rightPath, fpName, isFirstSync);
                        //conflictList = ctrl.getConflictList();
                        Dispatcher.BeginInvoke(DispatcherPriority.Background, (SendOrPostCallback)delegate { populateDataGrid(); btnConflict_OK.IsEnabled = true; }, null);
                        while (!isOk) { };
                        Dispatcher.BeginInvoke(DispatcherPriority.Background, (SendOrPostCallback)delegate { int errors = batchUILogUpdate(msgObj); this.refreshSyncTool(); }, null);
                        //Dispatcher.BeginInvoke(DispatcherPriority.Background, (SendOrPostCallback)delegate { btnSync.IsEnabled = true; }, null);

                        Dispatcher.BeginInvoke(DispatcherPriority.Background, (SendOrPostCallback)delegate { prgProgress.IsIndeterminate = false; }, null);
                        Dispatcher.BeginInvoke(DispatcherPriority.Background, (SendOrPostCallback)delegate { txtProgress.Text = "Completed."; }, null);
                    }
                    ).Start();
                }
                
            }
            catch (CustomException ex) //catch custom exception
            {
                System.Windows.Forms.MessageBox.Show(ex.Message, "Folder(s) not existent/selected error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            catch (Exception ex) //catch any uncaught exceptions
            {
                Console.WriteLine(ex.ToString());
            }
        }      
        private void RefreshFPBtn_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            // TODO: Add event handler implementation here.
            populateFolderPairsListView();
        }
        private void ClearFPBtn_Click(object sender, RoutedEventArgs e)
        {
            bool isChecked = false;
            foreach (FolderPair fp in folderPairs)
            {
                if (fp.IsToDelete)
                {
                    isChecked = true;
                    break;
                }
            }
            if (isChecked)
            {
                //Message box to confirm delete
                System.Windows.Forms.DialogResult msg = System.Windows.Forms.MessageBox.Show("Delete Folder Pairs?", "FAST", System.Windows.Forms.MessageBoxButtons.OKCancel);
                if (msg == System.Windows.Forms.DialogResult.OK)
                {
                    foreach (FolderPair fp in folderPairs)
                    {
                        if (fp.IsToDelete)
                        {
                            ctrl.removeFolderPairByName(fp.FPName);
                        }
                    }
                    CleanFolderPair();
                    refreshSyncTool();
                }
            }
            else
            {
                System.Windows.Forms.MessageBox.Show("No Folder Pair selected.");
            }
        }

          
        

        private int batchUILogUpdate(MessageLog msgObj)
        {
            //Updating txtbxAll.
            txtbxAll.AppendText("FAST system starting reconcile files now .....\n\n");
            txtbxAll.AppendText(msgObj.getAllMsg());
            txtbxAll.AppendText("\nFAST system ended reconcile files operations successfully.\n\n");
            txtbxAll.AppendText("--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\n");

            //txtbxAll.Select(txtbxAll.TextLength - 1, 0);
            txtbxAll.ScrollToEnd();

            //Updating other richtextbox
            if (msgObj.getMsgCount("CHANGE") > 0)
            {
                txtbxChange.AppendText("Changes performed during synchronization: \n\n");
                txtbxChange.AppendText(msgObj.getChangesMsg());
                txtbxChange.AppendText("--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------");

                //txtbxChange.Select(txtbxChange.TextLength - 1, 0);
                txtbxChange.ScrollToEnd();

                tbChanges.Header = "Changes(" + msgObj.getMsgCount("CHANGE") + ")";
            }
            else
            {
                //Set back to default.
                tbChanges.Header = "Changes";
            }

            if (msgObj.getMsgCount("CONFLICT") > 0)
            {
                txtbxConflict.AppendText("Conflicts founded during synchronization: \n\n");
                txtbxConflict.AppendText(msgObj.getConflictMsg());
                txtbxConflict.AppendText("--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------");

                //txtbxConflict.Select(txtbxConflict.TextLength - 1, 0);
                txtbxConflict.ScrollToEnd();

                tbConflicts.Header = "Conflicts(" + msgObj.getMsgCount("CONFLICT") + ")";
            }
            else
            {
                tbConflicts.Header = "Conflicts";
            }

            if (msgObj.getMsgCount("ERROR") > 0)
            {
                txtbxError.AppendText("Exception encountered during synchronization: \n\n");
                txtbxError.AppendText(msgObj.getErrorMsg());
                txtbxError.AppendText("--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------");

                //txtbxError.Select(txtbxError.TextLength - 1, 0);
                txtbxError.ScrollToEnd();

                tbError.Header = "Error(" + msgObj.getMsgCount("ERROR") + ")";
            }
            else
            {
                tbError.Header = "Error";
            }

            return msgObj.getMsgCount("ERROR");

        }
        private void Load_Last_IsVisibleChanged(object sender, System.Windows.DependencyPropertyChangedEventArgs e)
        {
        	// TODO: Add event handler implementation here.
			refreshSyncTool();
        }
        /*************************** Folder Pairs ****************************/
        private ObservableCollection<FolderPair> folderPairs = new ObservableCollection<FolderPair>();
        public ObservableCollection<FolderPair> FolderPairsCollection
        { get { return folderPairs; } }
        public class FolderPair
        {
            public string FPName { get; set; }
            public string FPLeftPath { get; set; }
            public string FPRightPath { get; set; }
            public string CreatedTime { get; set; }
            public string UpdatedTime { get; set; }
            public string LeftPathColor { get; set; }
            public string RightPathColor { get; set; }
            public bool IsToDelete { get; set; }
        }
        /*********************************************************************/
        //Cleanin
        private void CleanFolderPair()
        {
            ctrl.initializeNewFolderPair();
            cbxLeftFolder.Text = "";
            cbxRightFolder.Text = "";
            FPTxtBox.IsEnabled = true;
            FPTxtBox.Clear();
            FpNameLabel.Content = "";
            FpMsgLog.Content = "";
            clearFolderCompareListView();

        }
        private void refreshSyncTool()
        {
            string cur = currentState;
            if (currentState == "ViewNew")
            {
                CleanFolderPair();
            } else
            {
                string name = ctrl.getFolderPairName();
                if (!name.Equals(""))
                {
                    string leftPath = ctrl.getFPLeftFolderPath();
                    string rightPath = ctrl.getFPRightFolderPath();

                    if (Directory.Exists(leftPath) && Directory.Exists(rightPath))//Exception to check if folder pair folder paths exist in operating system
                    {
                        FpNameLabel.Content = ctrl.getFolderPairName() + "'s Folder Pair";
                        FpMsgLog.Content = ctrl.getFolderPairLog();
                        cbxLeftFolder.Text = leftPath;
                        cbxRightFolder.Text = rightPath;
                        FPTxtBox.IsEnabled = false;
                    }
                    else
                    {
                        CleanFolderPair();
                        System.Windows.Forms.MessageBox.Show("One or more folder no longer exist. Last Loaded Folder Pair fail to initialize.");//Exception to check if folder pair folder paths exist in operating system
                    }
                }
                else
                {
                    FPTxtBox.IsEnabled = true;
                }
                populateFolderPairsListView();


            }
        }

        public void populateDataGrid()
        {
            dgdConflict.ItemsSource = ctrl.getConflictList();
        }
        /*********************************************************************/
        //Populating Revert Version        
        private ObservableCollection<RevertVersion> revertVersions = new ObservableCollection<RevertVersion>();
        public ObservableCollection<RevertVersion> RevertVersionCollection { get { return revertVersions; } }
        public class RevertVersion
        {
            public int FileVersionNumber { get; set; }								        
            public string FileVersion{get; set;}
            public int VersionIdx{get; set;}
            public string Filesize{get; set;}
            public string LastmodifiedDate{get; set;}
            public string comments { get; set; }
        }

        //Populating FolderCompare
        private const int FILE_NOT_EXIST = 7; // copy file over
        private const int FILE_MODIFIED = 8;
        private const int FILE_IDENTICAL = 9;
        private ObservableCollection<StartNewListObject> newLeftObjects = new ObservableCollection<StartNewListObject>();
        private ObservableCollection<StartNewListObject> newRightObjects = new ObservableCollection<StartNewListObject>();
        public ObservableCollection<StartNewListObject> newRightListObjectCollection
        { get { return newLeftObjects; } }
        public ObservableCollection<StartNewListObject> newLeftListObjectCollection
        { get { return newRightObjects; } }
        public void populateLeftRightArrayList()
        {
            clearFolderCompareListView();

            int sizeL, sizeR;
            sizeL = leftListDetails.Count;
            sizeR = rightListDetails.Count;

            int start = 0;
            StartNewListObject newLeftObject = new StartNewListObject();
            StartNewListObject newRightObject = new StartNewListObject();

            for (int i = 0; i < sizeL; i++)
            {
                if (leftListDetails[i].isTypeFile())//if file
                {
                    newLeftObject = processFileListViewItem(((FileHandler)leftListDetails[i]), i, true);

                    if (((FileHandler)leftListDetails[i]).getFileStatus() != FILE_NOT_EXIST)
                    {
                        for (int j = start; j < sizeR; j++)
                        {
                            if (rightListDetails[j].isTypeFile()) //check is file
                            {
                                newRightObject = processFileListViewItem(((FileHandler)rightListDetails[j]), j, true);
                                if (((FileHandler)leftListDetails[i]).getSubFilePath().Equals(((FileHandler)rightListDetails[j]).getSubFilePath()))
                                {
                                    newLeftObjects.Add(newLeftObject);
                                    newRightObjects.Add(newRightObject);
                                    start = j + 1;
                                    break;
                                }
                                else
                                {
                                    newLeftObjects.Add(blankFileObject(false));
                                    newRightObjects.Add(newRightObject);
                                }
                            }
                            else//else if folder
                            {
                                newRightObject = processFolderListViewItem((FolderHandler)rightListDetails[j], j);
                                newLeftObjects.Add(blankFileObject(true));
                                newRightObjects.Add(newRightObject);
                            }
                        }
                    }
                    else
                    {
                        newLeftObjects.Add(newLeftObject);
                        newRightObjects.Add(blankFileObject(false));
                    }
                }
                else //ELSE TYPE IS FOLDER
                {
                    newLeftObject = processFolderListViewItem((FolderHandler)leftListDetails[i], i);

                    if (((FolderHandler)leftListDetails[i]).getFolderStatus() != FILE_NOT_EXIST)
                    {
                        for (int j = start; j < sizeR; j++)
                        {
                            if ((rightListDetails[j].isTypeFile() == false))
                            {
                                newRightObject = processFolderListViewItem((FolderHandler)rightListDetails[j], j);
                                if (((FolderHandler)leftListDetails[i]).getSubFolderPath().Equals(((FolderHandler)rightListDetails[j]).getSubFolderPath()))
                                {
                                    newLeftObjects.Add(newLeftObject);
                                    newRightObjects.Add(newRightObject);
                                    start = j + 1;
                                    break;
                                }
                                else
                                {
                                    newLeftObjects.Add(blankFileObject(true));
                                    newRightObjects.Add(newRightObject);
                                }
                            }
                            else
                            {
                                newRightObject = processFileListViewItem((FileHandler)rightListDetails[j], j, true);
                                newLeftObjects.Add(blankFileObject(true));
                                newRightObjects.Add(newRightObject);
                            }
                        }
                    }
                    else
                    {
                        newLeftObjects.Add(newLeftObject);
                        newRightObjects.Add(blankFileObject(true));
                    }
                }
                int count = newLeftObjects.Count;
                int count1 = newRightObjects.Count;
            }
            if (start < sizeR)
            {
                for (int k = start; k < sizeR; k++)
                {
                    newLeftObjects.Add(blankFileObject(false));
                    if (rightListDetails[k].isTypeFile())
                        newRightObject = processFileListViewItem((FileHandler)rightListDetails[k], k, true);
                    else
                        newRightObject = processFolderListViewItem((FolderHandler)rightListDetails[k], k);

                    newRightObjects.Add(newRightObject);
                }
            }

        }
        //Extracted Methods for Populate Left and Right Array
        private StartNewListObject blankFileObject(bool folder)
        {
            StartNewListObject newObject = new StartNewListObject();
            newObject.Folder = folder;
            //newObject.Indent = size;    
            //newObject.Name = "" + index;
            newObject.Filename = "";
            newObject.ToolTip = "";
            newObject.LastModifiedTime = "";

            return newObject;
        }
        private StartNewListObject processFolderListViewItem(FolderHandler folder, int index)
        {
            string dirName = folder.getSubFolderPath().Substring(1);
            StartNewListObject newObject = new StartNewListObject();
            string[] tokens = dirName.Split('\\');
            int size = tokens.Length;

            newObject.Folder = true;
            newObject.Indent = size;
            newObject.ToolTip = "";
            newObject.ImageIndex = 1;//display folder image
            newObject.Name = "" + index;
            newObject.LastModifiedTime = folder.getDi().LastWriteTime + "";
            newObject.Filename = folder.getDi().Name;
            newObject.Filetype = "Folder";
            return newObject;
        }
        private StartNewListObject processFileListViewItem(FileHandler file, int index, bool isFolderCompare)
        {
            string fileName = file.getSubFilePath().Substring(1);
            string[] tokens = fileName.Split('\\');
            int size = tokens.Length;
            StartNewListObject newObject = new StartNewListObject();
            newObject.Folder = false;
            newObject.Indent = size;
            newObject.ImageIndex = 0;
            newObject.Name = "" + index;
            newObject.Filename = file.getFi().Name;
            newObject.ToolTip = file.getFi().Name;
            newObject.LastModifiedTime = file.getLastModTime().ToString();
            newObject.Filetype = "File";
            newObject.Size = (file.getFileLength() / 1024).ToString();

            if (!isFolderCompare)
            {
                int versionIdx = file.getVersioningIdx();
                int versionCount = 0;
                if (versionIdx != -1)
                {
                    List<FileHandler> versionList = ctrl.getFVList()[file.getVersioningIdx()].getListOfFH();
                    versionCount = versionList.Count; //convert to method in main
                    newObject.NoOfVersion = versionCount.ToString();
                    int versionNum = 0;
                    foreach (FileHandler fh in versionList)
                    {
                        newObject.ToolTip += "\nv" + versionNum + " Comments:\n";
                        newObject.ToolTip += "" + fh.getComments() + "\n";
                        versionNum++;
                    }
                }
                else
                {
                    newObject.NoOfVersion = "0";
                    newObject.ToolTip += "\nNo Versions Exist";
                }
            }

            int fileStatus = file.getFileStatus();
            switch (fileStatus)
            {
                case FILE_NOT_EXIST:
                    newObject.Forecolor = "Red";
                    break;
                case FILE_MODIFIED:
                    newObject.Forecolor = "Blue";
                    break;
                case FILE_IDENTICAL:
                    newObject.Forecolor = "Green";
                    break;
            }

            return newObject;
        }
        public void clearFolderCompareListView()
        {
            newLeftObjects.Clear();
            newRightObjects.Clear();
            
        }
        public class StartNewListObject
        {
            public StartNewListObject()
            {
            }
            private string filename = "", filetype = "", size = "", lastModifiedTime = "", noOfVersion = "0";
            private string name = "", toolTip = "", forecolor = "";
            private bool folder;
            private int indent, imageIndex = -1;
            //Design
            private string fontWeight;
            private string imgSourceFolder;
            private string space = "";
            public string Space
            {
                get
                {
                    for (int i = 1; i <= Indent; i++)
                    {
                        space += "    ";
                    }
                    return space;
                }
                set { space = value; }
            }
            public string FontWeight
            {
                get
                {
                    if (imageIndex == 0)
                    {
                        return fontWeight = "normal";
                    }
                    else
                        return fontWeight = "bold";
                }
                set { fontWeight = value; }
            }
            public string ImgSourceFolder
            {
                get
                {
                    if (imageIndex == -1)
                    {
                        return imgSourceFolder = "";
                    }
                    else if (imageIndex == 0)
                    {
                        return imgSourceFolder = @"\Images\Start_New\file-icon.png";
                    }
                    else
                        return imgSourceFolder = @"\Images\Start_New\folder-icon.png"; ;
                }
                set { imgSourceFolder = value; }
            }
            public bool Folder
            {
                get { return folder; }
                set { folder = value; }
            }
            public string Forecolor
            {
                get { return forecolor; }
                set { forecolor = value; }
            }
            public string ToolTip
            {
                get { return toolTip; }
                set { toolTip = value; }
            }
            public string Name
            {
                get { return name; }
                set { name = value; }
            }


            public int ImageIndex
            {
                get { return imageIndex; }
                set { imageIndex = value; }
            }
            public int Indent
            {
                get { return indent; }
                set { indent = value; }
            }

            public string NoOfVersion
            {
                get
                {
                    if (imageIndex == -1)
                    {
                        return noOfVersion = "";
                    }
                    else if (imageIndex == 0)
                    {
                        return noOfVersion;
                    }
                    else
                        return noOfVersion = "0";
                }
                set { noOfVersion = value; }
            }

            public string LastModifiedTime
            {
                get { return lastModifiedTime; }
                set { lastModifiedTime = value; }
            }

            public string Size
            {
                get { return size; }
                set { size = value; }
            }

            public string Filetype
            {
                get { return filetype; }
                set { filetype = value; }
            }

            public string Filename
            {
                get { return filename; }
                set { filename = value; }
            }
        }
        private void btnConflict_OK_Click(object sender, RoutedEventArgs e)
        {
            this.isOk = true;
            btnConflict_OK.IsEnabled = false;
        }

        private string revertPath = "";

        private void btnRevertBrowse_Click(object sender, System.Windows.RoutedEventArgs e)
        {
        	// TODO: Add event handler implementation here.
			OpenFileDialog fileDialog = new OpenFileDialog();
			if(fileDialog.ShowDialog() == DialogResult.OK)
			{
				//System.Windows.Forms.MessageBox.Show(fileDialog.FileName.ToString());
                revertVersions.Clear();
                revertPath = fileDialog.FileName.ToString();
                cbxRevertFile.Text = revertPath;
                cbxRevertFile.Items.Add(revertPath);

                generateVersions(revertPath);
			}			
        }

        private void generateVersions(string revertPath)
        {
            FileVersioning fvHandler = new FileVersioning();
            FileInfo fi = new FileInfo(revertPath);
            txtCurrentFilename.Text = "Current Filename: " + fi.Name;
            txtSize.Text = "Size: " + fi.Length + "b";
            txtLastModTime.Text = "Last Modified Time: " + fi.LastWriteTime.ToString();
            List<FileVersioningList> fv = ctrl.getFVList();
            int idx = 0;
            foreach (FileVersioningList fvl in fv)
            {
                if (fvl.getFullFP().Equals(revertPath))
                {
                    btnSaveComment.Visibility = Visibility.Visible;
                    List<FileHandler> versions = fvl.getListOfFH();
                    //int vIdx = 0;
                    foreach (FileHandler fh in versions)
                    {
                        RevertVersion rv = new RevertVersion();
                        rv.FileVersionNumber = fvHandler.retrieveVersionNumber(fh.getFullFilePath());
                        fi = fh.getFi();
                        //if (ctrl.isCurrentRevertedVersion(idx,vIdx))
                            //rv.FileVersion = fi.Name + "[reverted copy]";
                        //else
                        rv.FileVersion = fi.Name;
                        rv.Filesize = fi.Length.ToString() + "b";

                        rv.VersionIdx = idx;

                        rv.LastmodifiedDate = fi.LastWriteTime.ToString();
                        rv.comments = fh.getComments();
                        revertVersions.Add(rv);

                        //vIdx++;
                    }
                    break;
                }
                else
                {
                    btnSaveComment.Visibility = Visibility.Hidden;
                }
                idx++;
            }
        }

        private void btnSaveComment_Click(object sender, RoutedEventArgs e)
        {
            if (revertVersions.Count > 0)
            {
                btnSaveComment.IsEnabled = false;
                new Thread(
                delegate()
                {
                    Dispatcher.BeginInvoke(DispatcherPriority.Background, (SendOrPostCallback)delegate { prgProgress3.IsIndeterminate = true; }, null);
                    Dispatcher.BeginInvoke(DispatcherPriority.Background, (SendOrPostCallback)delegate { txtProgress3.Text = "Saving..."; }, null);

                    Thread.Sleep(1000);
                    List<FileHandler> versions = ctrl.getFVList()[revertVersions[0].VersionIdx].getListOfFH();
                    int idx = 0;
                    foreach (RevertVersion rv in revertVersions)
                    {
                        versions[idx].setComments(rv.comments);
                        idx++;
                    }
                    ctrl.setVersionList(versions, revertVersions[0].VersionIdx);

                    Dispatcher.BeginInvoke(DispatcherPriority.Background, (SendOrPostCallback)delegate { prgProgress3.IsIndeterminate = false; }, null);
                    Dispatcher.BeginInvoke(DispatcherPriority.Background, (SendOrPostCallback)delegate { txtProgress3.Text = "Completed."; btnSaveComment.IsEnabled = true; }, null);
                }
                ).Start();

                /*
                List<FileHandler> versions = ctrl.getFVList()[revertVersions[0].VersionIdx].getListOfFH();
                int idx = 0;
                foreach (RevertVersion rv in revertVersions)
                {
                    versions[idx].setComments(rv.comments);
                    idx++;
                }
                ctrl.setVersionList(versions, revertVersions[0].VersionIdx);
                */ 
            }
            else
            {
                System.Windows.Forms.MessageBox.Show("No versions to add comments.");
            }
        }

        private void ListViewRevert_DoubleClick(object sender, MouseButtonEventArgs e)
        {
            ctrl.revertVersion(this.revertPath, revertVersions[0].VersionIdx, ((RevertVersion)((System.Windows.Controls.ListViewItem)sender).Content).FileVersionNumber);
            revertVersions.Clear();
            generateVersions(this.revertPath);
        }

    }
}